// 积分历史记录页面 
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Table, Card, Typography, Select, Spin, Button } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import MainLayout from '../../../components/MainLayout';
import Toast from '../../../components/Toast';
import pointsService from '../../../services/points';
import './PointsHistory.css';

const { Title } = Typography;
const { Option } = Select;

const PointsHistory = () => {
  const navigate = useNavigate();
  const [histories, setHistories] = useState([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });
  const [typeFilter, setTypeFilter] = useState('all');
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  // 返回积分首页
  const handleGoBack = () => {
    navigate('/points');
  };

  // 获取积分历史
  const fetchPointsHistory = async (page = 1, size = 20, type = 'all') => {
    try {
      setLoading(true);
      const response = await pointsService.getPointsHistory({ page, size, type });
      if (response.data.code === 200) {
        setHistories(response.data.data.histories || []);
        setPagination({
          current: response.data.data.pageNum,
          pageSize: response.data.data.pageSize,
          total: response.data.data.total
        });
      } else {
        showToastMessage('获取积分历史失败');
      }
    } catch (error) {
      showToastMessage('获取积分历史失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '积分数量',
      dataIndex: 'pointsAmount',
      key: 'pointsAmount',
      render: (amount) => (
        <span style={{ color: '#52c41a', fontWeight: 'bold' }}>
          +{amount}
        </span>
      )
    },
    {
      title: '积分类型',
      dataIndex: 'pointsTypeDesc',
      key: 'pointsTypeDesc'
    },
    {
      title: '状态',
      dataIndex: 'appliedStatusDesc',
      key: 'appliedStatusDesc'
    },
    {
      title: '获得时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => new Date(date).toLocaleString('zh-CN')
    },
    {
      title: '应用时间',
      dataIndex: 'appliedAt',
      key: 'appliedAt',
      render: (date) => date ? new Date(date).toLocaleString('zh-CN') : '-'
    }
  ];

  // 处理分页变化
  const handleTableChange = (paginationInfo) => {
    fetchPointsHistory(paginationInfo.current, paginationInfo.pageSize, typeFilter);
  };

  // 处理类型筛选变化
  const handleTypeChange = (value) => {
    setTypeFilter(value);
    fetchPointsHistory(1, pagination.pageSize, value);
  };

  useEffect(() => {
    fetchPointsHistory();
  }, []);

  return (
    <MainLayout>
      <div className="points-history-container">
        <Card>
          <div className="points-history-header" style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: '24px'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
              <Button 
                type="text" 
                icon={<ArrowLeftOutlined />}
                onClick={handleGoBack}
                style={{
                  color: '#1890ff',
                  fontSize: '16px',
                  padding: '4px 8px'
                }}
              >
                返回
              </Button>
              <Title level={2} style={{ margin: 0, color: '#1890ff' }}>
                积分历史
              </Title>
            </div>
            <Select
              value={typeFilter}
              onChange={handleTypeChange}
              style={{ width: 200 }}
              placeholder="选择积分类型"
            >
              <Option value="all">所有类型</Option>
              <Option value="network_settlement">局域网结算</Option>
              <Option value="resource_sale_commission">资源销售分成</Option>
            </Select>
          </div>

          <Table
            columns={columns}
            dataSource={histories}
            rowKey="historyId"
            loading={loading}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            }}
            onChange={handleTableChange}
          />
        </Card>

        {showToast && (
          <Toast 
            message={toastMessage} 
            onClose={() => setShowToast(false)} 
          />
        )}
      </div>
    </MainLayout>
  );
};

export default PointsHistory; 